#include "eventselectionmodel.h"
#include "logdbmanager.h"
#include "mainwindow.h"

EventSelectionModel::EventSelectionModel(QObject *parent) :
    QStandardItemModel(parent)
{
    setupModel();

    connect(this, SIGNAL(itemChanged(QStandardItem*)), this, SLOT(onItemChanged(QStandardItem*)));
    item(0)->setCheckState(Qt::Checked);
}

void EventSelectionModel::setupModel()
{
    int count = mainWindow->getStringTables().EventTypeStringTable.size();
    for (int i = 0; i < count; ++i) {
        QStandardItem *item = new QStandardItem(mainWindow->getStringTables().EventTypeStringTable[i]);
        item->setCheckable(true);
        appendRow(item);
    }

}

void EventSelectionModel::onItemChanged(QStandardItem *item)
{
    if (this->item(0) == item) {
        Qt::CheckState state = item->checkState();
        if (state != Qt::PartiallyChecked) {
            for (int i = 1; i < rowCount(); ++i) {
                this->item(i)->setCheckState(state);
            }
        }
    } else {
        bool all = true;
        bool none = true;
        for (int i = 1; i < rowCount(); ++i) {
            if (this->item(i)->checkState()==Qt::Checked)
                none = false;
            else
                all = false;
        }
        if (none) this->item(0)->setCheckState(Qt::Unchecked);
        else if (all) this->item(0)->setCheckState(Qt::Checked);
        else this->item(0)->setCheckState(Qt::PartiallyChecked);
    }
}
